<template>
  <div>
    <header class="search">
      <el-input v-model="filterText" placeholder="请输入分组或概览名称过滤" size="mini" class="searchInput"></el-input>
      <el-button
        v-if="($currentRole>2 && overviewGroupType == '0') || overviewGroupType == 1"
        type="primary"
        size="mini"
        class="addBtn"
        @click="handleCreateOpen"
      >新建</el-button>
    </header>
    <section>
      <div class="secItem data-grid-content">
        <el-tree
          ref="tree"
          v-loading="loading"
          element-loading-text="加载中"
          element-loading-spinner="el-icon-loading"
          :data="overviewNavigate"
          node-key="id"
          highlight-current
          check-on-click-node
          default-expand-all
          :expand-on-click-node="false"
        >
          <div
            class="custom-tree-node"
            :class="data.id === currentNodeKey?'active':''"
            slot-scope="{ node, data }"
          >
            <div
              :class="data.isLeafNode ? 'tree-node-label leaf-node':'tree-node-label'"
              @click="handleOverviewClick(node)"
            >
              <span>{{ node.data.label }}</span>
            </div>
            <div class="action-icon">
              <i class="el-icon-edit" @click="handleRenameOpen(node)"></i>
              <i class="el-icon-close" @click="handleDeleteOpen(node, data)"></i>
            </div>
          </div>
        </el-tree>
      </div>
    </section>
    <!-- 概览分组重命名弹框 -->
    <el-dialog
      class="rename-dialog"
      title="重命名"
      :modal="false"
      :visible.sync="renameVisible"
      width="30%"
    >
      <div>
        <el-form
          ref="renameForm"
          :model="renameForm"
          :rules="renameRules"
          label-width="80px"
          size="mini"
        >
          <el-form-item :label="renameLabel" prop="name">
            <el-input v-model="renameForm.name"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renameVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleRenameConfirm" size="mini">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 创建分组，创建概览 -->
    <el-dialog
      class="create-dialog"
      :title="createDialog.title"
      :modal="false"
      :visible.sync="createDialog.visible"
      width="30%"
    >
      <div>
        <el-form
          ref="createForm"
          :model="createForm"
          :rules="createRules"
          label-width="80px"
          size="mini"
        >
          <el-form-item label="新建类型" prop="type">
            <el-radio-group v-model="createForm.type">
              <el-radio :label="2">创建分组</el-radio>
              <el-radio :label="1">创建概览</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="createForm.type === 1">
            <el-form-item label="概览名称" prop="overviewName">
              <el-input v-model="createForm.overviewName"></el-input>
            </el-form-item>
            <el-form-item label="概览分组" prop="overview_group_id">
              <el-select v-model="createForm.overview_group_id" filterable placeholder="请选择">
                <el-option
                  v-for="item in groupList"
                  :key="item.id"
                  :label="item.overviewGroupName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item label="分组名称" prop="overviewGroupName">
              <el-input v-model="createForm.overviewGroupName"></el-input>
            </el-form-item>
            <el-form-item label="组内概览" prop="overviewIdList">
              <el-select
                v-model="createForm.overviewIdList"
                filterable
                clearable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in overviewList"
                  :key="item.id"
                  :label="item.overviewName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialog.visible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleCreateConfirm" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "gridTree",
  data() {
    return {
      filterText: "",
      overviewGroupType: 0,
      loading: false,
      renameVisible: false,
      renameForm: {
        name: ""
      },
      renameLabel: "分组名称",
      node: null,
      renameRules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      },
      createDialog: {
        title: "",
        visible: false
      },
      createForm: {
        type: 2,
        overviewName: "",
        overview_group_id: "",
        overviewGroupName: "",
        overviewIdList: []
      },
      createRules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      },
      count: 0, // 用于判断是否第一次加载
      currentNodeKey: null, // 用于highlight，选中节点
      overviewNavigate: [], // 概览导航
      groupList: [], // 概览分组list
      overviewList: [] // 概览list
    };
  },
  computed: {
    appItem() {
      return this.$store.state.global.appItem;
    }
  },
  props: {
    // 接受的个人概览还是公共概览
    overviewInfo: {
      type: Object
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    overviewInfo: {
      // 个人概览和公共概览切换
      handler(val) {
        this.overviewGroupType = val.value;
        this.handleOverviewNavigate();
      },
      immediate: true
    },
    appItem: {
      handler(val) {
        this.count = 0;
        this.currentNodeKey = null;
        this.$store.commit("SET_OVERVIEW_ITEM", null);
        this.handleOverviewNavigate();
      },
      deep: true,
      immediate: true
    },
    $route: {
      handler(val) {
        console.log(val, "route");
        let { path } = val;
        if (path.indexOf("dataCard") === -1) {
          this.currentNodeKey = null;
        }
      },
      immediate: true
    }
  },
  created() {},
  methods: {
    // 概览导航
    async handleOverviewNavigate() {
      this.loading = true;
      let { path } = this.$route;
      let data = {
        appId: this.appItem.appId,
        overviewGroupType: this.overviewGroupType,
        currentPage: 1,
        pageSize: 10000
      };
      try {
        let res = await this.$analysisApi.dataCard.overviewNavigate(data);
        if (res) {
          let { overviewGroupNavigateDTOS } = res.value;
          this.overviewNavigate = overviewGroupNavigateDTOS.map(item => {
            item.label = item.overviewGroupName;
            if (
              this.count === 0 &&
              path.indexOf("dataCard") > -1 &&
              this.overviewGroupType == 0
            ) {
              if (item.overviewDTOList.length > 0) {
                this.currentNodeKey = item.overviewDTOList[0].id;
                this.$store.commit(
                  "SET_OVERVIEW_ITEM",
                  item.overviewDTOList[0]
                );
              } else {
                this.$store.commit("SET_OVERVIEW_ITEM", null);
              }
              this.$router.push({
                path: `/dataAnalysis/dataCard`
              });
              this.count = 1;
            }
            item.children = item.overviewDTOList.map(overview => {
              overview.label = overview.overviewName;
              overview.isLeafNode = true;
              return overview;
            });
            item.isLeafNode = false;
            return item;
          });
          console.log(this.overviewNavigate, "this.overviewNavigate");
          this.loading = false;
        }
      } catch (e) {
        this.loading = false;
      }
    },
    // 分组 概览 重命名点击函数
    handleRenameOpen(node) {
      this.node = node;
      let { level } = this.node;
      this.renameLabel = level === 1 ? "分组名称" : "概览名称";
      this.renameForm.name = node.data.label;
      this.renameVisible = true;
	},
	// 分组 概览 删除点击函数
    handleDeleteOpen(node, data) {
      this.node = data;
      let txt = data.isLeafNode ? "概览" : "分组";
      this.$confirm(
        `删除${txt}后，不可恢复。建议手动调整后再进行删除操作`,
        "删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.handleDeleteConfirm(node);
      });
	},
	// 分组概览 重命名递交函数
    async handleRenameConfirm() {
      let { level } = this.node;
      let { id } = this.node.data;
      let { name } = this.renameForm;
      let data = {}, res = null;
      if (level === 1) {
        data = {
          id,
          overviewGroupName: name
        };
        res = await this.$analysisApi.dataCard.overviewGroupUpdate(data);
      } else {
        data = {
          id,
          overviewName: name
        };
        res = await this.$analysisApi.dataCard.overviewUpdate(data);
      }
      this.renameVisible = false;

      if (res) {
        this.node.data.label = name;
		this.node.data.overviewName = name;
        // this.$store.commit("SET_OVERVIEW_ITEM", this.node.data);
      }
	},
	// 分组概览 删除递交函数
    async handleDeleteConfirm(node) {
      let { level } = node;
      let { id } = node.data;
	  let res = null;
      if (level === 1) {
        res = await this.$analysisApi.dataCard.overviewGroupDelete({
          id
        });
      } else {
        res = await this.$analysisApi.dataCard.overviewDelete({
          id
        });
      }
      if (res) {
        const parent = node.parent;
        const children = parent.childNodes;
        const index = children.findIndex(d => {
          return d.data.id === id;
        });
		children.splice(index, 1);
		if(this.$store.state.global.overviewItem&&(node.data.id==this.$store.state.global.overviewItem.id)){
			this.$store.commit("SET_OVERVIEW_ITEM", null);
		}
      }
    },
    /*新建*/
    handleCreateOpen() {
      this.createDialog.title =
        this.overviewGroupType === 0
          ? "新建公共概览/分组"
          : "新建我的概览/分组";
      // 重置表单
      this.createForm = {
        type: 2,
        overviewName: "",
        overview_group_id: "",
        overviewGroupName: "",
        overviewIdList: []
      };

      this.createDialog.visible = true;
      this.handleQueryOverviewGroupList();
      this.handleQueryOverviewList();
    },
    // 概览分组列表
    async handleQueryOverviewGroupList() {
      let data = {
        appId: this.appItem.appId,
        overviewGroupType: this.overviewGroupType,
        currentPage: 1,
        pageSize: 10000
      };
      let res = await this.$analysisApi.dataCard.overviewGroupList(data);
      if (res) {
        let { list } = res.value;
        this.groupList = list;
      }
    },
    // 查询概览列表
    async handleQueryOverviewList() {
      let data = {
        appId: this.appItem.appId,
        overviewGroupType: this.overviewGroupType,
        currentPage: 1,
        pageSize: 10000
      };
      let res = await this.$analysisApi.dataCard.overviewList(data);
      if (res) {
        this.overviewList = res.value.list;
      }
    },
    async handleCreateConfirm() {
      let {
        type,
        overviewIdList,
        overviewGroupName,
        overviewName,
        overview_group_id
      } = this.createForm;
      let data = {};
      let res;
      if (type === 1) {
        data.overviewGroupType = this.overviewGroupType;
        data.overviewName = overviewName;
        data.overview_group_id = overview_group_id;
        res = await this.$analysisApi.dataCard.overviewAdd(data);
      } else {
        data.appId = this.appItem.appId;
        data.overviewGroupType = this.overviewGroupType;
        data.overviewGroupName = overviewGroupName;
        data.overviewIdList = overviewIdList;
        res = await this.$analysisApi.dataCard.overviewGroupAdd(data);
      }
      if (res) {
        this.handleOverviewNavigate();
        this.createDialog.visible = false;
      }
    },
    // 点击概览
    handleOverviewClick(node) {
      let { isLeafNode } = node.data;
      if (isLeafNode) {
        this.currentNodeKey = node.data.id;
        this.$emit("handlePanelBool");
        this.$store.commit("SET_OVERVIEW_ITEM", node.data);
        this.$router.push({
          path: `/dataAnalysis/dataCard`
          // query: {
          // 	id: node.data.id
          // }
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.btn-scale {
  -webkit-transform: scale(0.8);
  -moz-transform: scale(0.8);
  -ms-transform: scale(0.8);
  -o-transform: scale(0.8);
  transform: scale(0.8);
}
.rightP {
  color: #475669;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: calc(7rem);
  font-size: 14px;
  border-left: 0.01rem solid rgba($color: #909399, $alpha: 0.2);
  padding: 0.05rem;
  header {
    height: 0.5rem;
    line-height: 0.5rem;
    .searchInput {
      width: 80%;
      margin-right: 0.1rem;
    }
  }
  section::-webkit-scrollbar {
    display: none;
  }
  section {
    height: 6rem;
    overflow-y: scroll;
    scrollbar-width: none; /*Firefox*/
    -ms-overflow-style: none;
    .secItem {
    }
  }
}
.data-grid-content {
  padding: 0 10px 10px 10px;
  .el-tabs__nav-wrap {
    &::after {
      background-color: transparent;
    }
  }

  .el-tabs__item {
    /*color: rgb(255, 255, 255);*/

    &.is-active {
      color: #01b27a;
    }
  }

  .btn-content {
    text-align: center;
    margin-top: 5px;
  }

  /deep/.el-tree {
    /*background-color: transparent;*/
    /*color: #fff;*/
    padding: 0.2rem 0.1rem;
    .action-icon {
      opacity: 0;
      i {
        padding: 0.05rem;
        cursor: pointer;
        margin-left: 0.05rem;
        transition: all ease 0.5s;
        color: #01b27a;
      }
    }

    .el-tree-node:focus > .el-tree-node__content {
    }

    .el-tree-node__content {
      -webkit-transition: all 0.2s;
      -moz-transition: all 0.2s;
      -ms-transition: all 0.2s;
      -o-transition: all 0.2s;
      transition: all 0.2s;
      &:hover {
        .action-icon {
          opacity: 1;
        }
      }
      /deep/.el-icon-caret-right:before {
        content: "\e6e0";
      }
    }

    .custom-tree-node {
      flex-grow: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      /*font-size: 12px;*/
      overflow-x: hidden;

      .tree-node-label {
        -ms-text-overflow: ellipsis;
        text-overflow: ellipsis;
        overflow: hidden;
        font-size: 16px;
        &.leaf-node {
          font-weight: 500;
          font-size: 13px;
        }
      }

      .tree-node-icon {
        position: relative;
      }

      i[class^="el-icon-"] {
        /*font-size: 12px;*/
        width: auto;
      }
    }
  }

  .el-tree--highlight-current .el-tree-node > .el-tree-node__content {
    .custom-tree-node.active {
      .leaf-node {
        color: #01b27a;
      }
    }
  }

  /deep/.el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: transparent;
    /*color: #fff;*/

    .custom-tree-node.active {
      color: #01b27a;
    }
  }
}
</style>
<style lang="scss">
.el-popover.popover-scale {
  padding: 7px;
  min-width: 90px;
  .el-button {
    margin: 0;
  }
}
</style>
